package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.Application;
import android.view.View;
import android.widget.TimePicker;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.csweimei.rentmanagementtreasure.base.AppConfig;
import com.csweimei.rentmanagementtreasure.http.Repository;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.GlideHandler;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddDPVM extends BaseViewModel<Repository> {

    public AddDPVM(@NonNull Application application, Repository model) {
        super(application, model);
    }

    public ObservableField<String> text = new ObservableField<>("");
    public ObservableField<String> imgsrc = new ObservableField<>("");
    public ObservableField<String> addtime = new ObservableField<>(ValidateUtils.getCurDate());


    public BindingCommand back = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
       finish();
        }
    });


    public BindingCommand postData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (ValidateUtils.isEmptyString(text.get())){
                ToastUtils.showShort("请输入内容");
                return;
            }
            if (imgList.size() == 0){
                ToastUtils.showShort("请上传图片");
                return;
            }

            getQNYToken();


        }
    });

    public void post(){

    }

    private void saveData() {
        Map<String,String> map = AppConfig.getCurMap(model);
        map.put("text",text.get());
        map.put("imgsrc",imgsrc.get());
        map.put("addtime",addtime.get());
        model.adddaily(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult o) {
                        if (o.issucc){
                            ToastUtils.showShort("发布成功");
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private ArrayList<String> imgList = new ArrayList<>();

    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public List<String> uploadList = new ArrayList<>();
    private void uploadQNY(String token) {
        for (String l : imgList) {
            String suffix = l.substring(l.lastIndexOf("."));
            String key = "works/zgb/" + System.currentTimeMillis() + suffix;
            QiNiuYunUpload.uploadFileToQny(mActivity, l, token, key, new QiNiuYunUploadCallBack() {
                @Override
                public void onSuccess(String url) {
                    uploadList.add(url);

                    if (imgList.size() == uploadList.size()){
                        StringBuilder stringBuilder = new StringBuilder();
                        for (String localMedia : uploadList) {
                            stringBuilder.append(localMedia).append(",");
                        }
                        if (stringBuilder.toString().contains(",")){
                            imgsrc.set(stringBuilder.deleteCharAt(stringBuilder.length()-1).toString());
                        }else {
                            imgsrc.set(stringBuilder.toString());
                        }
                        saveData();
                    }

                }

                @Override
                public void onFail() {

                }

                @Override
                public void onProgress(String key, double progress) {

                }
            });
        }


    }



    public void setImgList(List<String> result) {
        imgList.clear();
        uploadList.clear();
        imgList.addAll(result);

    }
}
